+function () {
    "use strict";
    
    var oauth = new OAuth2();
    
    window.addEventListener("load", function () {
        $("#requestOAuth")[0].addEventListener("click", function (event) {
            event.preventDefault();
            
            chrome.identity.getAuthToken({
                interactive: true
            }, function (token) {
                var error;
                if (chrome.runtime.lastError) {
                    $("#OAuthError")[0].style.display = "";
                    error = chrome.runtime.lastError;
                    $("#OAuthError-reported")[0].innerHTML = error;
                    return;
                }
                
                if (!token) {
                    $("#OAuthError")[0].style.display = "";
                    $("#OAuthError-unknown")[0].style.display = "";
                    return;
                }
                
                $("#OAuthSuccess")[0].style.display = "";
                testYouTubeAccess();
            });
        }, false);
        
        $("#showOptions")[0].addEventListener("click", function (event) {
            event.preventDefault();
            location = chrome.extension.getURL("options.html");
        }, false);
    }, false);
    
    /**
     * Test whether the extension may or may not access the subscriptions list
     * of the current user.
     */
    function testYouTubeAccess() {
        var uri, params;
        uri = "https://gdata.youtube.com/feeds/api/users/default/" +
                "subscriptions";
        params = {
            "v": 2,
            "alt": "json",
            "max-results": 50
        };
        oauth.get(uri, params, function () {
            var backgroundPage, background;
            backgroundPage = chrome.extension.getBackgroundPage();
            background = new backgroundPage.Background();
            localStorage.setItem("useOAuth", "1");
            background.reload();
            $("#done")[0].style.display = "";
        }, function (requestOrError) {
            var response;
            if (requestOrError instanceof Error) {
                $("#YouTubeError-text")[0].innerHTML = requestOrError.message;
            } else {
                response = requestOrError.responseText;
                $("#YouTubeError-text")[0].innerHTML = response;
            }
            $("#YouTubeError")[0].style.display = "";
        });
    }
    
    /**
     * Returns a node list containing all nodes in the document matching the
     * provided CSS selector.
     * 
     * @param {string} selector CSS selector for selecting the nodes.
     * @returns {NodeList} Document nodes matching the specified selector.
     */
    function $(selector) {
        return document.querySelectorAll(selector);
    }
}();
